import { useEffect, useState } from 'react';
import './MyComment.css';
import commentApi from '@/apis/commentApi';
import { Button, Dialog, Image, List, PullRefresh, Rate, Tabs, Toast } from 'react-vant';
import { debounceAsync, getGoodsImagePath } from '@/utils/common';
import MyPromotePrice from '@/components/MyPromotePrice';
import { DeleteO } from '@react-vant/icons';
import { useNavigate } from 'react-router-dom';

const limit = 10;
const tabItems = [
  { key: 0, title: '待评论' },
  { key: 1, title: '已评论' },
];

const MyComment: React.FC = () => {
  const [page, setPage] = useState<number>(1);
  const [activeKey, setActiveKey] = useState<number>(0);
  const [finished, setFinished] = useState<boolean>(false);
  const [commentPenddings, setCommentPenddings] = useState<ResposneCommentPenddingDto[] | null>(
    null
  );
  const naviagte = useNavigate();

  const loadMore = async () => {
    const res = await commentApi.getCommentPenddingPagination(page, limit, activeKey);
    if (res.status >= 0) {
      setCommentPenddings((prev) => [...(prev ?? []), ...res.data.data]);
      setPage((prev) => prev + 1);
      setFinished(res.data.data.length < limit);
    }
  };

  const refresh = async () => {
    setCommentPenddings(() => []);
    setPage(1);
    setFinished(false);
  };

  const handleRate = async (v: number, id: number, odid: number) => {
    const formData = new FormData();
    formData.append('rate', v.toString());
    formData.append('goodId', id.toString());
    formData.append('orderDetailId', odid.toString());
    const res = await commentApi.addComment2(formData);
    if (res.status >= 0) {
      Toast.success('评论成功');
      setCommentPenddings((prev) =>
        prev!.filter((d) => d.goodComments.findIndex((d) => d.odid === odid) === -1)
      );
    }
  };

  const handleDelete = (id: number) => {
    Dialog.confirm({
      title: '提示',
      message: '你确定要删除该评论吗？',
      onCancel: () => console.log('cancel'),
      onConfirm: async () => {
        const res = await commentApi.deleteComment(id);
        if (res.status >= 0) {
          setCommentPenddings(
            commentPenddings!.filter((d) => d.goodComments.findIndex((d) => d.id === id) === -1)
          );
        }
      },
    });
  };

  const handleTabsChange = debounceAsync((name: number | string) => {
    setActiveKey(name as number);
    refresh();
  }, 100);

  return (
    <>
      <Tabs active={activeKey} onChange={handleTabsChange}>
        {tabItems.map((d) => (
          <Tabs.TabPane key={d.key} name={d.key} title={d.title}></Tabs.TabPane>
        ))}
      </Tabs>
      <PullRefresh onRefresh={refresh}>
        <List onLoad={loadMore} finished={finished} finishedText="没有更多了">
          {commentPenddings
            ?.filter((d) => d.goodComments.length > 0)
            .map((d, i) => (
              <div key={i} className="comment-pendding-card">
                <div className="pendding-card-time">{d.orderTime}</div>
                <div>
                  {d.goodComments.map((d) => (
                    <div key={d.good.id}>
                      {d.rate != null ? (
                        <div className="comment-pendding-delete">
                          <DeleteO onClick={() => handleDelete(d.id)} />
                        </div>
                      ) : null}

                      <div className="pendding-card-goods">
                        <div className="pendding-card-good-photo">
                          <Image src={getGoodsImagePath(d.good.id, d.good.photo)} />
                        </div>
                        <div className="pendding-card-good-info">
                          <div className="item-margin">
                            {d.good.name}&nbsp;&nbsp;{d.good.spec}
                          </div>
                          <div className="item-margin">
                            <MyPromotePrice
                              price={d.good.price}
                              propmotePrice={d.good.promotePrice}
                            />
                          </div>
                          <div className="center-align-container item-margin">
                            <span className="little-font">
                              {d.rate == null ? '快速评价' : '评分'}
                            </span>
                            <Rate
                              value={d.rate ?? 0}
                              onChange={(v: number) => {
                                if (!d.rate) handleRate(v, d.good.id, d.odid);
                              }}
                            />
                          </div>
                          {d.rate == null ? (
                            <div className="comment-btn">
                              <Button
                                size="small"
                                type="warning"
                                onClick={() =>
                                  naviagte('/addComment?gid=' + d.good.id + '&odid=' + d.odid)
                                }
                              >
                                去评论
                              </Button>
                            </div>
                          ) : null}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
        </List>
      </PullRefresh>
    </>
  );
};

export default MyComment;
